package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"shopping/model/mysql"
	"shopping/model/redis"
	"shopping/shoprpc/internal/svc"
	"shopping/shoprpc/shoprpc"
	"strconv"
	"time"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *shoprpc.ListRequest) (*shoprpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	if page <= 0 {
		page = 1
	}
	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize
	var good []mysql.Good
	get := redis.Rdb.Get("good" + strconv.Itoa(int(offset)))
	if get.Val() == "" {
		mysql.DB.Debug().Order("price desc").Order("created_at desc").Where("name like ?", "%"+in.Name+"%").Offset(int(offset)).Limit(int(pageSize)).Find(&good)
		marshal, _ := json.Marshal(good)
		redis.Rdb.Set("good"+strconv.Itoa(int(offset)), marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get.Val()), &good)
	}
	fmt.Println(good)
	var goods []*shoprpc.List
	for _, i := range good {
		list := shoprpc.List{
			Number: int64(i.Number),
			Name:   i.Name,
			Market: int64(i.Market),
			Price:  int64(i.Price),
			Image:  i.Image,
			UserId: int64(i.UserId),
			Id:     int64(i.ID),
		}
		goods = append(goods, &list)
	}
	fmt.Println(goods)
	return &shoprpc.ListResponse{List: goods}, nil
}
